package cn.lym.zxxx.config;

import java.util.HashMap;
import java.util.Map;

public class CurrentContextCache {
    private static Map<ClassLoader, Map<String, Object>> cache = new HashMap<>();

    private static Map<String, Object> getCacheMap() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Map<String, Object> map = cache.computeIfAbsent(classLoader, k -> new HashMap<>());
        return map;
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(String key, SFunction<T> sFn) {
        Map<String, Object> cacheMap = getCacheMap();
        Object obj = cacheMap.get(key);
        if (obj == null) {
            obj = sFn.create();
            cacheMap.put(key, obj);
        }
        return (T) obj;
    }

    @FunctionalInterface
    public static interface SFunction<T> {
        T create();
    }
}
